home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Internet Tools 1993 July / Internet Tools.iso / RockRidge / mail / mmdf / mmdf-IIb.43 / lib / dial / d_checksum.c < prev    next >
Encoding:
C/C++ Source or Header  |  1986-02-01  |  1.9 KB  |  113 lines

  1. # include  "d_returns.h"
  2.  
  3.  
  4.  
  5.  
  6.  
  7.  
  8.  
  9.  
  10. /*
  11.  *     D_CSCOMP
  12.  *
  13.  *     routine which computes the checksum for a packet and loads it into
  14.  *     the first 4 bytes as hex digits
  15.  *
  16.  *     text -- pointer to packet to be check summed.  this packet should
  17.  *             be complete except for the checksum field.  the bytes to
  18.  *             be included in the sum should start at text + 4;
  19.  *
  20.  *     length -- total length of the packet.  this count should include the
  21.  *               4 checksum digits but not the line terminator.
  22.  */
  23.  
  24. d_cscomp(text, length)
  25.   char  *text;
  26.   int  length;
  27.     {
  28.     register char  *cp;
  29.     register int  sum, value;
  30.     int  digit;
  31.  
  32. /*  add up the bytes  */
  33.  
  34.     cp = &text[4];
  35.     sum = 0;
  36.  
  37.     while (length > 4)
  38.       {
  39.       sum += *cp++;
  40.       length--;
  41.       }
  42.  
  43. /*  build and load the checksum  */
  44.  
  45.     cp = &text[3];
  46.  
  47.     for (digit = 0; digit <= 3; digit++)
  48.       {
  49.       value = sum & 017;
  50.       sum >>= 4;
  51.       *cp-- = d_tohex(value);
  52.       }
  53.  
  54.     return(D_OK);
  55.     }
  56.  
  57.  
  58.  
  59.  
  60.  
  61.  
  62.  
  63.  
  64.  
  65.  
  66.  
  67.  
  68. /*
  69.  *     D_CSCHECK
  70.  *
  71.  *     this routine checks that a packet has the correct checksum.  D_OK is
  72.  *     returned if it's alright, otherwise D_NO.
  73.  *
  74.  *     text -- pointer to the packet, including the checksum bytes
  75.  *
  76.  *     length -- number of bytes in the packet, excluding the line terminator
  77.  */
  78.  
  79. d_cscheck(text, length)
  80.   char  *text;
  81.   int  length;
  82.     {
  83.     register char  *cp;
  84.     register int  sum, cnum;
  85.     int  digit, chksum, value;
  86.  
  87. /*  sum up the bytes  */
  88.  
  89.     cp = &text[4];
  90.     sum = 0;
  91.  
  92.     for (cnum = 4; cnum < length; cnum++)
  93.       sum += *cp++;
  94.  
  95. /*  convert the checksum and see if ti matches what we've just computed  */
  96.  
  97.     cp = text;
  98.     chksum = 0;
  99.  
  100.     for (digit = 0; digit <= 3; digit++)
  101.       {
  102.       if ((value = d_fromhex(*cp++)) < 0)
  103.         return(D_NO);
  104.  
  105.       chksum = (chksum << 4) | value;
  106.       }
  107.  
  108.     if (chksum == sum)
  109.       return(D_OK);
  110.  
  111.     return(D_NO);
  112.     }
  113.